from django.shortcuts import render,redirect,reverse
from django.contrib.auth import login,logout,authenticate
from .form import Register_Form 
from django.http import HttpResponse
from .models import User

def register(request):
	if request.method == 'POST':
		form = Register_Form(request.POST) #获取POST方法传递到后端的数据
		if form.is_valid(): #如果表单验证成功,获取各内容的值
			telephone = form.cleaned_data.get('telephone') 
			password1 = form.cleaned_data.get('password1') 
			password2 = form.cleaned_data.get('password2')
			email = form.cleaned_data.get('email')
			username = form.cleaned_data.get('username')

			if password1 != password2:
				return HttpResponse('两次密码输入不一致')
			else:
				user = User.objects.create_user(telephone=telephone,password=password1,username=username,email=email)
				return redirect(reverse('blog_auth:login'))
	else:
		form = Register_Form()
		return render(request,'auth/register.html')

def logins(request):
	if request.method == 'POST':
		telephone = request.POST.get('telephone')
		password = request.POST.get('password')
		remember = request.POST.get('remember')
		user = authenticate(username=telephone,password=password)
		if user:
			if user.is_active:
				login(request,user)
				if remember:
					request.session.set_expiry(None)
				else:
					request.session.set_expiry(0)
				
				return redirect(reverse('blog:index'))
			else:
				return HttpResponse("账号已经被冻结")
		else:
			return HttpResponse('账号或密码错误')
	else:
		return render(request,'auth/login.html')


def super_user(request):
	User.objects.create_superuser(telephone=19999999999,password=111111,username='唐黎琦',email='496482665@qq.com')
	return HttpResponse('创建成功')

def cms_index(request):
	return render(request,'auth/profile.html')

def pub_blog(request):
	pass

def edit_category(request):
	pass